import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { NoticeEntity } from "@entity/system/notice.entity";
import { ListNoticeDTO, CreateNoticeDTO, UpdateNoticeDTO } from "@dto/system/notice.dto";
import { resBuild } from "@utils/resBuild";
import { checkKeyIsExist } from "@utils/serviceHelp";
import { getOperator } from "@utils";

@Provide()
export class NoticeService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(NoticeEntity)
  noticeEntity: Repository<NoticeEntity>;

  // 列表
  async list(queryParams: ListNoticeDTO) {
    const queryBuilder = this.noticeEntity.createQueryBuilder('entity');
    if(queryParams.noticeTitle) {
      queryBuilder.andWhere(`entity.noticeTitle like "%${queryParams.noticeTitle}%"`)
    }
    if(queryParams.createBy) {
      queryBuilder.andWhere(`entity.createBy like "%${queryParams.createBy}%"`)
    }
    if(queryParams.noticeType) {
      queryBuilder.andWhere(`entity.noticeType = :noticeType`, { noticeType: queryParams.noticeType})
    }

    if(queryParams.pageNum && queryParams.pageSize) {
      queryBuilder.skip((queryParams.pageNum - 1) * queryParams.pageSize).take(queryParams.pageSize)
    }

    queryBuilder.addOrderBy('entity.createTime', 'DESC')
    const [rows, total] = await queryBuilder.getManyAndCount()
    return resBuild.list(rows, total)
  }

  // 添加
  async create(notice: CreateNoticeDTO) {
    // 新增之前先判断是否已存在
    await checkKeyIsExist(this.noticeEntity,'noticeTitle', notice.noticeTitle)
     const myEntity = this.noticeEntity.create(notice);
     myEntity.setCreateBy(getOperator(this.ctx))
    await this.noticeEntity.save(myEntity);
    return resBuild.success()
  }

  // 删除
  async delete(noticeId: string) {
    const ids = noticeId.split(',').map(id => Number(id));
    await this.noticeEntity.delete(ids);
    return resBuild.success()
  }

  // 修改
  async update(notice: UpdateNoticeDTO) {
    const myEntity = this.noticeEntity.create(notice);
    myEntity.setUpdateBy(getOperator(this.ctx))
    await this.noticeEntity.save(notice);
    return resBuild.success()
  }

  // 详情
  async detail(noticeId: number) {
    const detailInfo = await this.noticeEntity.findOneBy({
      noticeId,
    });
    return resBuild.data(detailInfo)
  }
}
